from flask import Blueprint, jsonify, request

from db import db1
from views.cates import get_data

bp_user = Blueprint("adminuser", __name__)


# 添加角色
@bp_user.route('/roleM', methods=['POST', 'GET'])
def roleM():
    data = get_data()
    sql = "select id from roles where name='%s'" % (data['name'])
    res = sql.find(sql)
    if res:
        return jsonify({'code': 20010})
    else:
        sql1 = "insert into roles values (0,'%s')" % (data['name'])
        db1.update(sql1)
        return jsonify({'code': 200})


@bp_user.route('/resourceM', methods=['POST', 'GET'])
def resourceM():
    if request.method == "POST":
        # 获取参数
        data = get_data()
        # 判断角色是否重复
        sql = "select id from resources where name='%s'" % (data['name'])
        res = db1.find(sql)
        if res:
            # 存在返回错误信息
            return jsonify({"code": 20010})
        else:
            sql1 = "insert into resources values(0,'%s','%s')" % (data['name'], data['url'])
            # 不存在添加
            db1.update(sql1)
            return jsonify({"code": 200})
    else:
        # 获取roleid，如果存在查询此角色对应的资源ids
        roleid = request.args.get('id')
        if roleid:
            sql = "select resource_id from roles_resource where role_id=%d" % (int(roleid))
            res = db1.find_all(sql)
            list = []

            for i in res:
                list.append(i['resource_id'])
        else:
            sql = "select * from resources"
            list = db1.find_all(sql)
        return jsonify({"code": 200, 'list': list})